import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:magic_car/jiance/insurance.dart';
import 'package:magic_car/util/HttpHelper.dart';
import 'package:magic_car/util/colors.dart';
import 'package:magic_car/util/config.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_bluetooth_serial/flutter_bluetooth_serial.dart';
import 'package:toast/toast.dart';
import 'dart:convert';
import 'dart:typed_data';
import 'dart:io';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:dio/dio.dart';
import 'package:cached_network_image/cached_network_image.dart';

class BluetoothDeviceListEntry extends ListTile {
  BluetoothDeviceListEntry({
    @required BluetoothDevice device,
    int rssi,
    GestureTapCallback onTap,
    GestureLongPressCallback onLongPress,
    bool enabled = true,
  }) : super(
          onTap: onTap,
          onLongPress: onLongPress,
          enabled: enabled,
          leading:
              Icon(Icons.devices), // @TODO . !BluetoothClass! class aware icon
          title: Text(device.name ?? "Unknown device"),
          subtitle: Text(device.address.toString()),
          trailing: Row(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              rssi != null
                  ? Container(
                      margin: new EdgeInsets.all(8.0),
                      child: DefaultTextStyle(
                        style: _computeTextStyle(rssi),
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          children: <Widget>[
                            Text(rssi.toString()),
                            Text('dBm'),
                          ],
                        ),
                      ),
                    )
                  : Container(width: 0, height: 0),
              device.isConnected
                  ? Icon(Icons.import_export)
                  : Container(width: 0, height: 0),
              device.isBonded
                  ? Icon(Icons.link)
                  : Container(width: 0, height: 0),
            ],
          ),
        );

  static TextStyle _computeTextStyle(int rssi) {
    /**/ if (rssi >= -35)
      return TextStyle(color: Colors.greenAccent[700]);
    else if (rssi >= -45)
      return TextStyle(
          color: Color.lerp(
              Colors.greenAccent[700], Colors.lightGreen, -(rssi + 35) / 10));
    else if (rssi >= -55)
      return TextStyle(
          color: Color.lerp(
              Colors.lightGreen, Colors.lime[600], -(rssi + 45) / 10));
    else if (rssi >= -65)
      return TextStyle(
          color: Color.lerp(Colors.lime[600], Colors.amber, -(rssi + 55) / 10));
    else if (rssi >= -75)
      return TextStyle(
          color: Color.lerp(
              Colors.amber, Colors.deepOrangeAccent, -(rssi + 65) / 10));
    else if (rssi >= -85)
      return TextStyle(
          color: Color.lerp(
              Colors.deepOrangeAccent, Colors.redAccent, -(rssi + 75) / 10));
    else
      /*code symetry*/
      return TextStyle(color: Colors.redAccent);
  }
}

enum _DeviceAvailability {
  no,
  maybe,
  yes,
}

class _DeviceWithAvailability extends BluetoothDevice {
  BluetoothDevice device;
  _DeviceAvailability availability;
  int rssi;

  _DeviceWithAvailability(this.device, this.availability, [this.rssi]);
}

//obd 检测页面
class OBDPage extends StatefulWidget {
  final String oid;
  OBDPage(this.oid);

  @override
  _MyHomePageState createState() => new _MyHomePageState(this.oid);
}

class _MyHomePageState extends State<OBDPage> {
  List formList;
  List problemCode = [];
  List waitproblemCode = [];
  List imgArr = [];

  FlutterBluetoothSerial flutterBlue = FlutterBluetoothSerial.instance;
  // FlutterBlue flutterBlue = FlutterBlue.instance;
  BluetoothDevice device;
  BluetoothConnection connection;
  bool isconnect = false;
  String sendCode = "ATZ";
  String sendModel = "03";
  String sendModel_desc = '3';
  bool canupload = false;
  bool obdfinish = false;

  Map orders = new Map();
  final String oid;
  _MyHomePageState(this.oid);
  initState() {
    super.initState();
    // startScandevice();

    // loaddata();
  }

  photo() async {
    showModalBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return Padding(
              padding: new EdgeInsets.fromLTRB(0, 0, 0, 0),
              child: Container(
                height: 130,
                child: new Column(children: <Widget>[
                  new Container(
                      decoration: new BoxDecoration(
                          border: Border(
                              bottom: BorderSide(
                                  width: 1, color: Color(0xffe5e5e5)))),
                      height: 50,
                      child: Center(
                          child:
                              Text('上传图片?', style: TextStyle(fontSize: 16)))),
                  new Container(
                      decoration: new BoxDecoration(
                          border: Border(
                              bottom: BorderSide(
                                  width: 1, color: Color(0xffe5e5e5)))),
                      height: 40,
                      child: new GestureDetector(
                          behavior: HitTestBehavior.opaque,
                          onTap: () async {
                            Navigator.pop(context);
                            //connect();
                            uploadImgs('', 1);
                          },
                          child: Center(
                              child: Text('相机',
                                  style: TextStyle(
                                      fontSize: 16, color: Colors.red))))),
                  new Container(
                      height: 40,
                      child: new GestureDetector(
                          behavior: HitTestBehavior.opaque,
                          onTap: () {
                            Navigator.pop(context);
                            uploadImgs('', 2);
                          },
                          child: Center(
                              child:
                                  Text('相册', style: TextStyle(fontSize: 16))))),
                ]),
              ));
        });
  }

  // _saveImg(avatar) async {
  //   if (Platform.isAndroid) {
  //     // 检查并请求权限
  //     PermissionStatus status = await PermissionHandler()
  //         .checkPermissionStatus(PermissionGroup.storage);
  //     if (PermissionStatus.granted != status) {
  //       PermissionHandler().requestPermissions(<PermissionGroup>[
  //         PermissionGroup.storage,
  //       ]);
  //     } else {
  //       var response = await Dio()
  //           .get(avatar, options: Options(responseType: ResponseType.bytes));
  //       // final result =
  //       // await ImageGallerySaver.saveFile(Uint8List.fromList(response.data));
  //       final result = await ImageGallerySaver.saveImage(
  //           Uint8List.fromList(response.data));
  //       print('result:$result');
  //       if (result != null) {
  //       } else {}
  //     }
  //   } else {
  //     PermissionStatus status = await PermissionHandler()
  //         .checkPermissionStatus(PermissionGroup.photos);
  //     if (PermissionStatus.granted != status) {
  //       PermissionHandler().requestPermissions(<PermissionGroup>[
  //         PermissionGroup.photos,
  //       ]);
  //     } else {
  //       var response = await Dio()
  //           .get(avatar, options: Options(responseType: ResponseType.bytes));
  //       // final result =
  //       // await ImageGallerySaver.saveFile(Uint8List.fromList(response.data));
  //       final result = await ImageGallerySaver.saveImage(
  //           Uint8List.fromList(response.data));
  //       print('result:$result');
  //       if (result != null) {
  //       } else {}
  //     }
  //   }
  //   //ImageGallerySaver.saveFile(file)
  //   // final result = await ImageGallerySaver.saveImage(image);

  //   // if(Utils.isEmpty(result)){
  //   //   print('保存失败');
  //   // }else{
  //   //   print('保存成功');
  //   // }
  // }
  _saveImg(avatar) async {
    if (Platform.isAndroid) {
      if (await Permission.storage.request().isGranted) {
        var response = await Dio()
            .get(avatar, options: Options(responseType: ResponseType.bytes));
        // final result =
        // await ImageGallerySaver.saveFile(Uint8List.fromList(response.data));
        final result = await ImageGallerySaver.saveImage(
            Uint8List.fromList(response.data));
        print('result:$result');
      }
      // 检查并请求权限
      // PermissionStatus status = await PermissionHandler()
      //     .checkPermissionStatus(PermissionGroup.storage);
      // if (PermissionStatus.granted != status) {
      //   PermissionHandler().requestPermissions(<PermissionGroup>[
      //     PermissionGroup.storage,
      //   ]);
      // } else {
      //   var response = await Dio()
      //       .get(avatar, options: Options(responseType: ResponseType.bytes));
      //   // final result =
      //   // await ImageGallerySaver.saveFile(Uint8List.fromList(response.data));
      //   final result = await ImageGallerySaver.saveImage(
      //       Uint8List.fromList(response.data));
      //   print('result:$result');
      //   if (result != null) {
      //   } else {}
      // }
    } else {
      if (await Permission.photos.request().isGranted) {
        var response = await Dio()
            .get(avatar, options: Options(responseType: ResponseType.bytes));
        // final result =
        // await ImageGallerySaver.saveFile(Uint8List.fromList(response.data));
        final result = await ImageGallerySaver.saveImage(
            Uint8List.fromList(response.data));
        print('result:$result');
      }
      // PermissionStatus status = await PermissionHandler()
      //     .checkPermissionStatus(PermissionGroup.photos);
      // if (PermissionStatus.granted != status) {
      //   PermissionHandler().requestPermissions(<PermissionGroup>[
      //     PermissionGroup.photos,
      //   ]);
      // } else {
      //   var response = await Dio()
      //       .get(avatar, options: Options(responseType: ResponseType.bytes));
      //   // final result =
      //   // await ImageGallerySaver.saveFile(Uint8List.fromList(response.data));
      //   final result = await ImageGallerySaver.saveImage(
      //       Uint8List.fromList(response.data));
      //   print('result:$result');
      //   if (result != null) {
      //   } else {}
      // }
    }
    //ImageGallerySaver.saveFile(file)
    // final result = await ImageGallerySaver.saveImage(image);

    // if(Utils.isEmpty(result)){
    //   print('保存失败');
    // }else{
    //   print('保存成功');
    // }
  }

  //上传图片
  uploadImgs(item, type) async {
    var image;

    if (type == 1) {
      image = await ImagePicker.pickImage(source: ImageSource.camera);
    } else {
      image = await ImagePicker.pickImage(source: ImageSource.gallery);
    }
    if (image == null) return;
    // File _files = await FlutterNativeImage.compressImage(image.path);
    File _files = image;

    Map<String, String> map = new Map();

    HttpHelper.upLoadImage(_files, (data) {
      // print('data');
      if (data.containsKey('code')) {
        Toast.show(data['msg'], context);
      } else {
        imgArr.add(data['url']);
        setState(() {
          imgArr = imgArr;
        });
      }
    }, params: map);
  }

  showAlerts(texts) {
    showModalBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return Padding(
              padding: new EdgeInsets.fromLTRB(0, 0, 0, 0),
              child: Container(
                height: 130,
                child: new Column(children: <Widget>[
                  new Container(
                      decoration: new BoxDecoration(
                          border: Border(
                              bottom: BorderSide(
                                  width: 1, color: Color(0xffe5e5e5)))),
                      height: 50,
                      child: Center(
                          child: Text('找到设备' + texts + '是否连接？',
                              style: TextStyle(fontSize: 16)))),
                  new Container(
                      decoration: new BoxDecoration(
                          border: Border(
                              bottom: BorderSide(
                                  width: 1, color: Color(0xffe5e5e5)))),
                      height: 40,
                      child: new GestureDetector(
                          behavior: HitTestBehavior.opaque,
                          onTap: () async {
                            Navigator.pop(context);
                            connectOBD();
                            // startconnetc();
                          },
                          child: Center(
                              child: Text('连接',
                                  style: TextStyle(
                                      fontSize: 16, color: Colors.red))))),
                  new Container(
                      height: 40,
                      child: new GestureDetector(
                          behavior: HitTestBehavior.opaque,
                          onTap: () {
                            Navigator.pop(context);
                          },
                          child: Center(
                              child:
                                  Text('取消', style: TextStyle(fontSize: 16))))),
                ]),
              ));
        });
  }

  List<_DeviceWithAvailability> deviceslist = List<_DeviceWithAvailability>();
  bool finddevice = false;

  //开始扫描蓝牙设备
  startScandevice() async {
    Toast.show('扫描设备中，请稍等', context);
    flutterBlue.getBondedDevices().then((List<BluetoothDevice> bondedDevices) {
      deviceslist = bondedDevices
          .map(
            (device) =>
                _DeviceWithAvailability(device, _DeviceAvailability.yes),
          )
          .toList();
      deviceslist.forEach((element) {
        print(element.device.name);
        if (element.device.name.startsWith('OBD')) {
          device = element.device;
          finddevice = true;

          // BluetoothConnection.toAddress(device.address).then((value) => {
          //       connection = value
          //       //connectOBD()
          //     });
          connectOBD();
        } else {}
      });

      if (finddevice == false) {
        //没有找到设备，需要进行扫描
        flutterBlue.startDiscovery().listen((r) {
          print('扫描到设备');
          print(r.device.name);

          if (r.device.name != null && r.device.name.startsWith('OBD')) {
            print('找到目标设备');
            flutterBlue.cancelDiscovery(); //停止扫描
            showAlerts(r.device.name);
            device = r.device;
          }
        });
      }
    });
  }
  //连接obd
  // connectOBD(){

  // }
  int num = 1;
  String recieve = "";
  List<int> bytedata = [];
  connectOBD() async {
    //flutterBlue.getBondedDevices();
    if (isconnect == false) {
      BluetoothConnection.toAddress(device.address).then((_connection) async {
        print('Connected to the device');
        Toast.show('连接成功，正在请求数据，请稍后', context);
        EasyLoading.show(status: "数据获取中");
         Future.delayed(Duration(seconds: 3), () {
            EasyLoading.dismiss();
            //loadpage.close();
           
          });
        connection = _connection;
        setState(() {
          isconnect = true;
        });

        writedata(sendCode);

        await connection.output.allSent;
        //connection.input.listen(_onDataReceived).onDone(() {});

        connection.input.listen((Uint8List datas) {
         // EasyLoading.dismiss();
          print('接收字节$datas');
          String recieve = Utf8Codec().decode(datas).toString().trim();
          if (!recieve.contains('>')) {
            //结束
            for (int i = 0; i < datas.length; i++) {
              bytedata.add(datas[i]);
            }
            return;
          } else {
            for (int i = 0; i < datas.length; i++) {
              bytedata.add(datas[i]);
            }
            recieve = Utf8Codec().decode(bytedata).toString().trim();
            bytedata = []; //清空数组
          }

          print('接收值$recieve');
          if (!recieve.contains('>') && sendCode != "0100") {
            //接收值，结束标志
            return; //知道接收到结束符才处理信息
          }

          if (sendCode == "ATZ") {
            if (recieve[0] == "E") {
              print('ATZ成功');
              sendCode = "ATL0";
              writedata(sendCode);
            } else {
              writedata(sendCode);
            }
          } else if (sendCode == "ATL0") {
            if (recieve[0] == "A") {
              print('ATL0成功');
              print(recieve[4]);
              sendCode = "ATE1";
              writedata(sendCode);
            } else {
              writedata(sendCode);
            }
          } else if (sendCode == "ATE1") {
            if (recieve[2] == "E") {
              print('ATE1成功');
              sendCode = "ATH0";
              writedata(sendCode);
            } else {
              writedata(sendCode);
            }
          } else if (sendCode == "ATH0") {
            if (recieve[2] == "H") {
              print('ATH0成功');
              sendCode = "ATSP" + num.toString();
              // num = 6;
              // sendCode = "ATSP6";
              // num = 6;
              writedata(sendCode);
            } else {
              writedata(sendCode);
            }
          } else if (sendCode == "ATSP" + num.toString()) {
            if (recieve.contains('ATSP') && recieve.contains('OK')) {
              sendCode = "0100";
              writedata(sendCode);
            } else {
              if (num < 9) {
                num++;
              } else {
                num = 1;
              }
              sendCode = "ATSP" + num.toString();
              writedata(sendCode);
            }
          } else if (sendCode == "0100") {
            if (recieve.contains('41 00')) {
              sendCode = sendModel;
              writedata(sendCode);
            } else {
              if (num < 9) {
                num++;
              } else {
                num = 1;
              }
              sendCode = "ATSP" + num.toString();
              writedata(sendCode);
            }
          }
          // else if (sendCode == "0100") {
          //   if (recieve.contains('41 00')) {
          //     sendCode = "03";
          //     writedata(sendCode);
          //   }
          // }
          // else if (sendCode == "03") {
          //   print('故障代码$recieve');
          // }
          // if (recieve.contains('41 00')) {
          //   sendCode = sendModel;
          //   writedata(sendCode);
          // }
          //recieve.contains('43')
          if (sendCode == sendModel) {
            print('检测到故障代码$recieve');
            // print('组装之后的故障码$codes');
            // problemCode.add({'code': '接收值', 'descrble': recieve});
            // setState(() {
            //   problemCode = problemCode;
            // });

            // Toast.show('检测到故障代码$recieve', context);
            // if (recieve.contains('4'+sendModel))
            if (recieve.contains('4' + sendModel_desc)) {
              print('111检测到故障代码$recieve');
              // List temp_arr_str = recieve.split(' ');
              // // print(temp_arr_str[0].toString());
              // // print(temp_arr_str[1].toString());
              // String codes = 'P';
              // for (int i = 0; i < temp_arr_str.length; i++) {
              //   if (temp_arr_str[i] == "01") {
              //     if (temp_arr_str[i + 1] != '01') {
              //       codes = codes + temp_arr_str[i] + temp_arr_str[i + 1];
              //       codes = codes + ',P';
              //     }
              //   }
              // }

              getcodedesc(recieve);
            } else {
            //  EasyLoading.dismiss();
              print('未检测到故障码');
            }
          }
        }).onDone(() {
          print('Disconnected by remote request');
        });
      }).catchError((error) {
        Toast.show('设备连接失败，请重试', context);
        // connectOBD();//如果失败重新连接
        print('Cannot connect, exception occured');
        print(error);
      });

      // writedata(sendCode);

      // await connection.output.allSent;
      // //connection.input.listen(_onDataReceived).onDone(() {});

      // connection.input.listen((Uint8List datas) {
      //   print('接收字节$datas');
      //   String recieve = Utf8Codec().decode(datas).toString().trim();
      //   if (!recieve.contains('>')) {
      //     //结束
      //     for (int i = 0; i < datas.length; i++) {
      //       bytedata.add(datas[i]);
      //     }
      //     return;
      //   } else {
      //     for (int i = 0; i < datas.length; i++) {
      //       bytedata.add(datas[i]);
      //     }
      //     recieve = Utf8Codec().decode(bytedata).toString().trim();
      //     bytedata = []; //清空数组
      //   }

      //   print('接收值$recieve');
      //   if (!recieve.contains('>') && sendCode != "0100") {
      //     //接收值，结束标志
      //     return; //知道接收到结束符才处理信息
      //   }

      //   if (sendCode == "ATZ") {
      //     if (recieve[0] == "E") {
      //       print('ATZ成功');
      //       sendCode = "ATL0";
      //       writedata(sendCode);
      //     } else {
      //       writedata(sendCode);
      //     }
      //   } else if (sendCode == "ATL0") {
      //     if (recieve[0] == "A") {
      //       print('ATL0成功');
      //       print(recieve[4]);
      //       sendCode = "ATE1";
      //       writedata(sendCode);
      //     } else {
      //       writedata(sendCode);
      //     }
      //   } else if (sendCode == "ATE1") {
      //     if (recieve[2] == "E") {
      //       print('ATE1成功');
      //       sendCode = "ATH0";
      //       writedata(sendCode);
      //     } else {
      //       writedata(sendCode);
      //     }
      //   } else if (sendCode == "ATH0") {
      //     if (recieve[2] == "H") {
      //       print('ATH0成功');
      //       sendCode = "ATSP" + num.toString();
      //       // num = 6;
      //       // sendCode = "ATSP6";
      //       // num = 6;
      //       writedata(sendCode);
      //     } else {
      //       writedata(sendCode);
      //     }
      //   } else if (sendCode == "ATSP" + num.toString()) {
      //     if (recieve.contains('ATSP') && recieve.contains('OK')) {
      //       sendCode = "0100";
      //       writedata(sendCode);
      //     } else {
      //       if (num < 9) {
      //         num++;
      //       } else {
      //         num = 1;
      //       }
      //       sendCode = "ATSP" + num.toString();
      //       writedata(sendCode);
      //     }
      //   }
      //   else if (sendCode == "0100") {
      //     if (recieve.contains('41 00')) {
      //       sendCode = sendModel;
      //     writedata(sendCode);
      //     }else{
      //       if (num < 9) {
      //         num++;
      //       } else {
      //         num = 1;
      //       }
      //       sendCode = "ATSP" + num.toString();
      //       writedata(sendCode);
      //     }
      //   }
      //   // else if (sendCode == "03") {
      //   //   print('故障代码$recieve');
      //   // }
      //   // if(sendCode=="0100")
      //   // if (recieve.contains('41 00')) {
      //   //   sendCode = sendModel;
      //   //   writedata(sendCode);
      //   // }else {
      //   //    if (num < 9) {
      //   //       num++;
      //   //     } else {
      //   //       num = 1;
      //   //     }
      //   //     sendCode = "ATSP" + num.toString();
      //   //     writedata(sendCode);
      //   // }
      //   //recieve.contains('43')
      //   if (sendCode == sendModel) {
      //     print('检测到故障代码$recieve');
      //     // print('组装之后的故障码$codes');
      //     problemCode.add({'code': '接收值', 'descrble': recieve});
      //     setState(() {
      //       problemCode = problemCode;
      //     });

      //     // Toast.show('检测到故障代码$recieve', context);
      //     if (recieve.contains('43')) {
      //       List temp_arr_str = recieve.split(' ');
      //       print(temp_arr_str[0].toString());
      //       print(temp_arr_str[1].toString());
      //       String codes = 'P';
      //       for (int i = 0; i < temp_arr_str.length; i++) {
      //         if (temp_arr_str[i] == "01") {
      //           if (temp_arr_str[i + 1] != '01') {
      //             codes = codes + temp_arr_str[i] + temp_arr_str[i + 1];
      //             codes = codes + ',P';
      //           }
      //         }
      //       }

      //       getcodedesc(codes);
      //     } else {
      //       print('未检测到故障码');
      //     }
      //   }
      // }).onDone(() {
      //   print('Disconnected by remote request');
      // });
    } else {
      sendCode = "ATZ";
      writedata(sendCode);
    }
    //List<BluetoothService> services = await device.discoverServices();
  }

  //发送数据
  writedata(str) async {
    List<int> b = Utf8Codec().encode(str + '\r');
    print('写入值$b');
    print('写入值转换：$str');

    connection.output.add(b);
    //cwrite.flush();
  }

  getcodedesc(code) {
    setState(() {
      obdfinish = true;
    });
    if (sendModel_desc == '3') {
      setState(() {
        problemCode = [];
      });
    } else {
      setState(() {
        waitproblemCode = [];
      });
    }
    // formList[deviceindex]['value'] = '接收故障码：' + code_string;
    Map<String, String> map = new Map();
    map['code'] = code;
    map['type'] = sendModel_desc;

    print('请求故障码$map');

    String api = HttpHelper.API_GetTroubleCode;

    HttpHelper.post(api, (data) async {
      if (data != null) {
        print(data);
        Toast.show(data["msg"], context);
        if (data['code'].toString() == "1") {
          var str = '';
          for (int i = 0; i < data['info'].length; i++) {
            if (sendModel_desc == '3') {
              problemCode.add(data['info'][i]);
            } else {
              waitproblemCode.add(data['info'][i]);
            }
            // print(data['info'][i]['code']);
            str = str +
                '故障码：' +
                data['info'][i]['code'] +
                ',故障描述：' +
                data['info'][i]['descrble'] +
                '\r';
          }

          setState(() {
            problemCode = problemCode;
            waitproblemCode = waitproblemCode;
          });
          if (problemCode.length > 0 || waitproblemCode.length > 0) {
            setState(() {
              canupload = true;
            });
          } else {
            canupload = false;
          }
        }

        // pref.setStringList('userinfo', data["info"]);

      }
    }, params: map);
  }

  //加载数据
  loaddata() async {
    Map<String, String> map = new Map();
    map['oid'] = this.oid;
    //  SharedPreferences pref = await SharedPreferences.getInstance();
    //  map["id"]=pref.getString('uid');
    //  map["type"]="0";

    HttpHelper.post(HttpHelper.API_OrderDetail, (data) async {
      if (data != null) {
        if (data["code"].toString() == "1") {
          List oldlist = formList;
          var orderinfo = data["info"];
          for (var i = 0; i < oldlist.length; i++) {
            var item = oldlist[i];
            var str = "";
            if (i == 0)
              str = orderinfo["name"];
            else if (i == 1)
              str = orderinfo["phone_num"];
            else if (i == 2)
              str = orderinfo["name"];
            else if (i == 3)
              str = orderinfo["phone_num"];
            else if (i == 4)
              str = orderinfo["add_time"];
            else
              str = orderinfo["address"] + orderinfo["address"];

            item["sub_title"] = str;
          }

          setState(() {
            formList = oldlist;
            // orders=data["info"];
          });
          //pref.setStringList('userinfo', data["info"]);

        }
      }
    }, params: map);
  }

  //更新质保信息
  uptorderinfo(type) {
    //1 符合质保，0 不可质保
    Map<String, Object> map = new Map();
    map['oid'] = this.oid;
    map['noneed'] = type;
    HttpHelper.post(HttpHelper.API_SubObdData, (data) async {
      if (data != null) {
        print(data);
        // Toast.show(data["info"], context);
        if (data["code"].toString() == "1") {
          if (type == "1") {
            Toast.show('上传成功，请继续完成检测', context);
            Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
              return new InsurancePapularinspects(this.oid, 1, {}, false);
            }));
          } else {
            Toast.show('信息更新成功', context);
            Navigator.pop(context);
          }
          // Navigator.pop(context);
          // //可以继续检测
          // if (waitproblemCode.length > 0 || problemCode.length > 0) {
          //   Toast.show(data["info"], context);
          // } else {
          //   Toast.show('上传成功，请继续完成检测', context);
          //   Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
          //     return new InsurancePapularinspects(this.oid, 1, {}, false);
          //   }));
          // }
        } else {
          Toast.show(data['msg'], context);
        }
      }
    }, params: map);
  }

  Widget buildcontent() {
    List<Widget> tiles = [];
    Widget content;

    tiles.add(
      Padding(
        padding: new EdgeInsets.fromLTRB(15, 0, 0, 5),
        child: new Container(
          height: 32,
          width: double.infinity - 20,

          //color: Colors.red,
          child: new Align(
              alignment: Alignment.centerLeft,
              child: new Text(
                '通用故障码：',
                style: TextStyle(fontSize: 15),
              )),
        ),
      ),
    );

    if (problemCode.length == 0) {
      tiles.add(
        Padding(
          padding: new EdgeInsets.fromLTRB(15, 0, 0, 5),
          child: new Container(
            height: 32,
            width: double.infinity - 20,

            //color: Colors.red,
            child: new Align(
                alignment: Alignment.centerLeft,
                child: new Text(
                  '未检测到故障码',
                  style: TextStyle(fontSize: 13),
                )),
          ),
        ),
      );
    } else {
      for (var i = 0; i < problemCode.length; i++) {
        tiles.add(
          Padding(
            padding: new EdgeInsets.fromLTRB(15, 0, 0, 5),
            child: new Container(
              height: 32,
              width: double.infinity - 20,

              //color: Colors.red,
              child: new Align(
                  alignment: Alignment.centerLeft,
                  child: new Text(problemCode[i]['code'] +
                      ':' +
                      problemCode[i]['descrble'])),
            ),
          ),
        );
      }
    }

    tiles.add(
      Padding(
        padding: new EdgeInsets.fromLTRB(15, 0, 0, 5),
        child: new Container(
          height: 32,
          width: double.infinity - 20,

          //color: Colors.red,
          child: new Align(
              alignment: Alignment.centerLeft,
              child: new Text(
                '待定故障码：',
                style: TextStyle(fontSize: 15),
              )),
        ),
      ),
    );

    if (waitproblemCode.length == 0) {
      tiles.add(
        Padding(
          padding: new EdgeInsets.fromLTRB(15, 0, 0, 5),
          child: new Container(
            height: 32,
            width: double.infinity - 20,

            //color: Colors.red,
            child: new Align(
                alignment: Alignment.centerLeft,
                child: new Text(
                  '未检测到故障码',
                  style: TextStyle(fontSize: 13),
                )),
          ),
        ),
      );
    } else {
      for (var i = 0; i < waitproblemCode.length; i++) {
        tiles.add(
          Padding(
            padding: new EdgeInsets.fromLTRB(15, 0, 0, 5),
            child: new Container(
              height: 32,
              width: double.infinity - 20,

              //color: Colors.red,
              child: new Align(
                  alignment: Alignment.centerLeft,
                  child: new Text(waitproblemCode[i]['code'] +
                      ',' +
                      waitproblemCode[i]['descrble'])),
            ),
          ),
        );
      }
    }

    tiles.add(Padding(
      padding: new EdgeInsets.fromLTRB(15, 3, 15, 5),
      child: Text(
        '请在车辆上电发动机不启动的时候使用obd读取故障码,检测完成后请同时拍照上传检测大师APP的检测结果！',
        style: TextStyle(color: Colors.red),
      ),
    ));

    tiles.add(
      Padding(
          padding: new EdgeInsets.fromLTRB(15, 3, 15, 5),
          child: new Row(
            children: [
              Expanded(
                  flex: 1,
                  child: Padding(
                      padding: new EdgeInsets.fromLTRB(0, 0, 15, 0),
                      child: new FlatButton(
                          shape: RoundedRectangleBorder(
                              side: BorderSide.none,
                              borderRadius:
                                  BorderRadius.all(Radius.circular(20))),
                          color: Colours.app_main,
                          onPressed: () async {
                            sendCode = "ATZ";
                            sendModel = "03";
                            sendModel_desc = '3';
                            if (isconnect == false) {
                              startScandevice();
                              // Future <bool> isavaliable =  flutterBlue.isAvailable;
                              //  if(isavaliable==false){

                              //  }
                              //   flutterBlue.isAvailable.then((value) => {
                              //    startScandevice()
                              //   });
                            } else {
                              connectOBD();
                              writedata(sendCode);
                            }
                          },
                          child: new Text(
                            '连接并检测',
                            style: TextStyle(color: Colors.white),
                          )))),
              Expanded(
                  flex: 1,
                  child: Padding(
                      padding: new EdgeInsets.fromLTRB(15, 0, 0, 0),
                      child: new FlatButton(
                          shape: RoundedRectangleBorder(
                              side: BorderSide.none,
                              borderRadius:
                                  BorderRadius.all(Radius.circular(20))),
                          color: Colours.app_main,
                          onPressed: () {
                            sendCode = "ATZ";
                            sendModel = "07";
                            sendModel_desc = '7';
                            writedata(sendCode);
                          },
                          child: new Text(
                            '待定故障码',
                            style: TextStyle(color: Colors.white),
                          ))))
            ],
          )),
    );
    // tiles.add(
    //   Padding(
    //       padding: new EdgeInsets.fromLTRB(15, 3, 0, 5),

    //       child:
    //        new FlatButton(
    //           shape: RoundedRectangleBorder(
    //               side: BorderSide.none,
    //               borderRadius: BorderRadius.all(Radius.circular(20))),
    //           color: Color.fromRGBO(27, 182, 251, 1),
    //           onPressed: () {
    //             // sendCode = "ATZ";
    //             // sendModel = "07";
    //             // sendModel_desc = '7';
    //             // writedata(sendCode);
    //           },
    //           child: new Text(
    //             '待定故障码',
    //             style: TextStyle(color: Colors.white),
    //           ))
    //           ),
    // );

    tiles.add(
      Padding(
          padding: new EdgeInsets.fromLTRB(15, 3, 15, 5),
          child: new Row(
            children: [
              Expanded(
                  flex: 1,
                  child: Padding(
                      padding: new EdgeInsets.fromLTRB(0, 0, 15, 0),
                      child: new FlatButton(
                          shape: RoundedRectangleBorder(
                              side: BorderSide.none,
                              borderRadius:
                                  BorderRadius.all(Radius.circular(20))),
                          color: Colours.app_main,
                          onPressed: () {
                          photo();
                           // uptorderinfo("1");
                          },
                          // child: new Text(
                          //   '符合质保',
                          //   style: TextStyle(color: Colors.white),
                          // )
                          child: new Text(
                            '拍照（检测大师）',
                            style: TextStyle(color: Colors.white),
                          )
                          ))),
                           Expanded(
                  flex: 1,
                  child: Padding(
                      padding: new EdgeInsets.fromLTRB(15, 0, 0, 0),
                      child: new FlatButton(
                          shape: RoundedRectangleBorder(
                              side: BorderSide.none,
                              borderRadius:
                                  BorderRadius.all(Radius.circular(20))),
                          color: obdfinish
                              ? Color.fromRGBO(27, 182, 251, 1)
                              : Colors.grey,
                          onPressed: () {
                            uploadobdCode();
                            if (!obdfinish) {
                              //obd没有检测完成
                              Toast.show('请先完成obd检测', context);
                            } else {
                              // if (canupload) {
                              //   //上传报告

                              // } else {
                              //   //继续检测
                              // }

                              uploadobdCode();
                            }
                            
                          },
                          child: new Text(
                            '上传报告',
                            // canupload ? '上传报告' : '继续检测',
                            style: TextStyle(color: Colors.white),
                          ))))
              // Expanded(
              //     flex: 1,
              //     child: Padding(
              //         padding: new EdgeInsets.fromLTRB(15, 0, 0, 0),
              //         child: new FlatButton(
              //             shape: RoundedRectangleBorder(
              //                 side: BorderSide.none,
              //                 borderRadius:
              //                     BorderRadius.all(Radius.circular(20))),
              //             // color: obdfinish
              //             //     ? Color.fromRGBO(27, 182, 251, 1)
              //             //     : Colors.grey,
              //             color: Color.fromRGBO(27, 182, 251, 1),
              //             onPressed: () {
              //             //  uptorderinfo("0");
              //               uploadobdCode();
              //               if (!obdfinish) {
              //                 //obd没有检测完成
              //                 Toast.show('请先完成obd检测', context);
              //               } else {
              //                 // if (canupload) {
              //                 //   //上传报告

              //                 // } else {
              //                 //   //继续检测
              //                 // }

              //                 uploadobdCode();
              //                // uptorderinfo();
              //               }
              //             },
              //             child: new Text(
              //              // '不符合质保',
              //                canupload ? '上传报告' : '继续检测',
              //               style: TextStyle(color: Colors.white),
              //             ))))
            ],
          )),
    );
    List<Widget> tiless = [];
    for (var i = 0; i < imgArr.length; i++) {
      // List temp1 = imgArr[i] as List;
      tiless.add(Padding(
        padding: new EdgeInsets.fromLTRB(5, 0, 0, 10),
        child: GestureDetector(
            onLongPress: () {
              print('识别长按手势');
              // showdeleteAlert(item, i);
            },
            onTap: () {
              print('点击查看图片');
              Navigator.of(context).push(
                NinePicture(imgArr, i),
              );
            },
            child: Image.network(imgArr[i], width: 100, height: 100)),
      ));
    }
    Widget contents = new Wrap(spacing: 0, runSpacing: 0, children: tiless);
    tiles.add(contents);

    content = new Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: tiles //重点在这里，因为用编辑器写Column生成的children后面会跟一个<Widget>[]，
        //此时如果我们直接把生成的tiles放在<Widget>[]中是会报一个类型不匹配的错误，把<Widget>[]删了就可以了
        );
    return content;
  }

  //上传报告
  uploadobdCode() {
    if (imgArr.length == 0) {
      Toast.show('请上传检测大师结果图片', context);
      return;
    }
    var imgStr = "";
    for (var i = 0; i < imgArr.length; i++) {
      if (i == imgArr.length - 1) {
        imgStr += imgArr[i];
      } else {
        imgStr = imgStr + imgArr[i] + ',';
      }
    }
    Map checkdata = {
      'img': imgStr,
      'codes': problemCode,
      'waitcodes': waitproblemCode
    };
    Map<String, Object> map = new Map();
    map["obddata"] = jsonEncode(checkdata);
    map['oid'] = this.oid;
    if (problemCode.length == 0 && waitproblemCode.length == 0) {
      map['noneed'] = '1';
    } else {
      map['noneed'] = '0';
    }
    HttpHelper.post(HttpHelper.API_SubObdData, (data) async {
      if (data != null) {
        print(data);
        // Toast.show(data["info"], context);
        if (data["code"].toString() == "1") {
          Navigator.pop(context);
          //可以继续检测
          if (waitproblemCode.length > 0 || problemCode.length > 0) {
            Toast.show(data["info"], context);
          } else {
            Toast.show('上传成功，请继续完成检测', context);
            Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
              return new InsurancePapularinspects(this.oid, 1, {}, false);
            }));
          }
        } else {}
      }
    }, params: map);
  }

  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: new AppBar(
          titleSpacing: 0,
          title: new Text(
            'OBD检测',
            style: TextStyle(fontSize: Config.title_size),
          ),
          backgroundColor: Colors.white,
          iconTheme: new IconThemeData(color: Colors.black),
          elevation: 0,
          // backgroundColor: Color.fromRGBO(255, 204, 48, 1),
        ),
        body: new Center(
            child: Container(
          decoration: new BoxDecoration(
            color: Colours.base_page_color,
          ),
          child: Padding(
              padding: new EdgeInsets.fromLTRB(0, 10, 0, 0),
              child: new ListView(
                children: <Widget>[buildcontent()],
              )),
        )));
  }
}

class NinePicture<T> extends PopupRoute<T> {
  final String barrierLabel;
  final List picList;
  final int index;
  int startX;
  int endX;

  NinePicture(this.picList, this.index, {this.barrierLabel});

  @override
  Duration get transitionDuration => Duration(milliseconds: 2000);

  @override
  @override
  Color get barrierColor => Colors.black54;

  @override
  bool get barrierDismissible => true;

  AnimationController _animationController;

  @override
  AnimationController createAnimationController() {
    assert(_animationController == null);
    _animationController =
        BottomSheet.createAnimationController(navigator.overlay);
    return _animationController;
  }

  @override
  Widget buildPage(BuildContext context, Animation<double> animation,
      Animation<double> secondaryAnimation) {
    return MediaQuery.removePadding(
      removeTop: true,
      context: context,
      child: GestureDetector(
        child: AnimatedBuilder(
          animation: animation,
          builder: (BuildContext context, Widget child) => GestureDetector(
            onTap: () {
              Navigator.pop(context);
            },
            child: _PictureWidget(picList, index),
          ),
        ),
      ),
    );
  }
}

class _PictureWidget extends StatefulWidget {
  final List picList;
  final int index;

  _PictureWidget(this.picList, this.index);

  @override
  State createState() {
    return _PictureWidgetState();
  }
}

class _PictureWidgetState extends State<_PictureWidget> {
  int startX = 0;
  int endX = 0;
  int index = 0;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    index = widget.index;
  }

  @override
  Widget build(BuildContext context) {
    return new Material(
      color: Colors.transparent,
      child: new Container(
        width: double.infinity,
        child: Stack(
          children: <Widget>[
            GestureDetector(
              child: Center(
                child: CachedNetworkImage(
                  imageUrl: widget.picList[index],
                  fit: BoxFit.cover,
                ),
              ),
              onHorizontalDragDown: (detail) {
                startX = detail.globalPosition.dx.toInt();
              },
              onHorizontalDragUpdate: (detail) {
                endX = detail.globalPosition.dx.toInt();
              },
              onHorizontalDragEnd: (detail) {
                _getIndex(endX - startX);
                setState(() {});
              },
              onHorizontalDragCancel: () {},
            ),
            Align(
              alignment: Alignment.bottomCenter,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: List.generate(
                  widget.picList.length,
                  (i) => GestureDetector(
                    child: CircleAvatar(
                      foregroundColor: Theme.of(context).primaryColor,
                      radius: 8.0,
                      backgroundColor: index == i
                          ? Theme.of(context).primaryColor
                          : Colors.white,
                    ),
                    onTap: () {
                      setState(() {
                        startX = endX = 0;
                        index = i;
                      });
                    },
                  ),
                ).toList(),
              ),
            )
          ],
        ),
        alignment: Alignment.center,
      ),
    );
  }

  void _getIndex(int delta) {
    if (delta > 50) {
      setState(() {
        index--;
        index = index.clamp(0, widget.picList.length - 1);
      });
    } else if (delta < 50) {
      setState(() {
        index++;
        index = index.clamp(0, widget.picList.length - 1);
      });
    }
  }
}
